<template>
  <div class="guide-detail-container">
    <!-- 状态栏 -->
    <div class="status-bar">
      <span class="time">12:30</span>
      <div class="status-icons">
        <span class="signal">📶</span>
        <span class="wifi">📶</span>
        <span class="battery">🔋</span>
      </div>
    </div>

    <!-- 头部 -->
    <div class="header">
      <div class="header-left">
        <div class="back-button" @click="goBack">←</div>
        <h1 class="page-title">指南详情</h1>
      </div>
      <div class="header-right">
        <div class="menu-icon">⋯</div>
        <div class="target-icon">🎯</div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <div class="loading-text">加载中...</div>
    </div>

    <!-- 指南详情内容 -->
    <div v-else-if="guideDetail" class="guide-content">
      <!-- 指南标题 -->
      <div class="guide-header">
        <h2 class="guide-title">{{ guideDetail.Title }}</h2>
        <div class="guide-meta">
          <span class="guide-date">{{ formatDate(guideDetail.CreatedAt) }}</span>
          <span class="guide-views">{{ guideDetail.Views }}人已查看</span>
        </div>
      </div>

      <!-- 指南内容 -->
      <div class="guide-body">
        <div class="content-section">
          <h3 class="section-title">内容概述</h3>
          <p class="content-text">{{ guideDetail.Content }}</p>
        </div>

        <div v-if="guideDetail.Steps" class="content-section">
          <h3 class="section-title">详细步骤</h3>
          <div class="steps-content" v-html="formatSteps(guideDetail.Steps)"></div>
        </div>

        <div class="content-section">
          <h3 class="section-title">医院信息</h3>
          <p class="hospital-info">{{ guideDetail.HospitalName }}</p>
        </div>
      </div>

      <!-- 收藏按钮 -->
      <div class="collection-section">
        <button 
          class="collection-btn" 
          :class="{ 'collected': isCollected }"
          @click="toggleCollection"
          :disabled="collectionLoading"
        >
          <span class="star-icon" :class="{ 'star-filled': isCollected }">
            {{ isCollected ? '★' : '☆' }}
          </span>
          <span class="collection-text">
            {{ isCollected ? '已收藏' : '收藏' }}
          </span>
          <div v-if="collectionLoading" class="loading-dot"></div>
        </button>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <div class="error-icon">⚠️</div>
      <div class="error-text">指南详情加载失败</div>
      <button class="retry-button" @click="fetchGuideDetail">重新加载</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import OutpatientApi from '@/utils/Interceptors'

const router = useRouter()
const route = useRoute()

// 定义指南详情类型
interface GuideDetail {
  GuideId: number
  Title: string
  Content: string
  HospitalId: number
  HospitalName: string
  Steps: string
  Views: number
  CreatedAt: string
  UpdatedAt: string
}

// 响应数据接口
interface ApiResponse {
  code: number
  msg: string
  data: GuideDetail
}

// 状态管理
const loading = ref(false)
const guideDetail = ref<GuideDetail | null>(null)

// 收藏相关状态
const isCollected = ref(false)
const collectionLoading = ref(false)

// 获取指南详情
const fetchGuideDetail = async () => {
  const guideId = route.params.id
  console.log('获取指南详情，指南ID:', guideId)
  
  if (!guideId) {
    showToast({
      message: '指南ID无效',
      position: 'middle',
      duration: 2000
    })
    return
  }

  try {
    loading.value = true
    console.log('开始获取指南详情...')
    // 使用查询参数而不是路径参数
    const response = await OutpatientApi.get('/api/ConsultationCategory/GetGuideById', {
      params: { guideId: guideId }
    })
    console.log('API响应:', response)
    const result: ApiResponse = response.data
    console.log('解析后的数据:', result)
    
    if (result.code === 200) {
      guideDetail.value = result.data
      console.log('指南详情加载成功:', result.data)
      // 获取收藏状态
      await checkCollectionStatus()
    } else {
      console.error('API返回错误:', result.msg)
      showToast({
        message: result.msg || '获取指南详情失败',
        position: 'middle',
        duration: 2000
      })
    }
  } catch (error: any) {
    console.error('获取指南详情失败:', error)
    let errorMessage = '网络错误，请稍后重试'
    
    // 检查是否是网络错误
    if (error.response) {
      // 服务器返回了错误状态码
      console.error('服务器错误:', error.response.status, error.response.data)
      if (error.response.status === 404) {
        errorMessage = '指南不存在或已被删除'
      } else if (error.response.status === 500) {
        errorMessage = '服务器内部错误'
      } else {
        errorMessage = `请求失败 (${error.response.status})`
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      console.error('网络连接错误:', error.request)
      errorMessage = '无法连接到服务器，请检查网络连接'
    } else {
      // 其他错误
      console.error('其他错误:', error.message)
      errorMessage = '请求配置错误'
    }
    
    showToast({
      message: errorMessage,
      position: 'middle',
      duration: 3000
    })
  } finally {
    loading.value = false
  }
}

// 检查收藏状态
const checkCollectionStatus = async () => {
  if (!guideDetail.value) return
  
  try {
    // 这里使用固定的用户ID，实际项目中应该从用户状态获取
    const userId = 1
    const guideId = guideDetail.value.GuideId
    const itemType = 'guide'
    
    const response = await OutpatientApi.get('/api/ConsultationCategory/CheckUserCollection', {
      params: { userId, guideId, itemType }
    })
    
    if (response.data.code === 200) {
      isCollected.value = response.data.data
      console.log('收藏状态检查成功:', isCollected.value)
    } else {
      console.error('检查收藏状态失败:', response.data.msg)
    }
  } catch (error: any) {
    console.error('检查收藏状态失败:', error)
  }
}

// 切换收藏状态
const toggleCollection = async () => {
  if (!guideDetail.value || collectionLoading.value) return
  
  try {
    collectionLoading.value = true
    const userId = 1 // 固定用户ID，实际项目中应该从用户状态获取
    const guideId = guideDetail.value.GuideId
    const itemType = 'guide'
    
    if (isCollected.value) {
      // 取消收藏
      const response = await OutpatientApi.delete('/api/ConsultationCategory/RemoveUserCollection', {
        params: { userId, guideId, itemType }
      })
      
      if (response.data.code === 200) {
        isCollected.value = false
        showToast({
          message: '取消收藏成功',
          position: 'middle',
          duration: 2000
        })
      } else {
        showToast({
          message: response.data.msg || '取消收藏失败',
          position: 'middle',
          duration: 2000
        })
      }
    } else {
      // 添加收藏
      const response = await OutpatientApi.post('/api/ConsultationCategory/AddUserCollection', {
        UserId: userId,
        GuideId: guideId,
        ItemType: itemType
      })
      
      if (response.data.code === 200) {
        isCollected.value = true
        showToast({
          message: '收藏成功',
          position: 'middle',
          duration: 2000
        })
      } else {
        showToast({
          message: response.data.msg || '收藏失败',
          position: 'middle',
          duration: 2000
        })
      }
    }
  } catch (error: any) {
    console.error('收藏操作失败:', error)
    showToast({
      message: '操作失败，请稍后重试',
      position: 'middle',
      duration: 2000
    })
  } finally {
    collectionLoading.value = false
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 格式化步骤内容
const formatSteps = (steps: string) => {
  // 将换行符转换为HTML换行
  return steps.replace(/\r\n/g, '<br>').replace(/\n/g, '<br>')
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchGuideDetail()
})
</script>

<style scoped>
.guide-detail-container {
  min-height: 100vh;
  background: #f8f9fa;
  position: relative;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: white;
  font-size: 14px;
  color: #333;
}

.status-icons {
  display: flex;
  gap: 5px;
}

/* 头部 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: white;
  border-bottom: 1px solid #eee;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.back-button {
  font-size: 20px;
  color: #333;
  cursor: pointer;
  padding: 5px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.header-right {
  display: flex;
  gap: 15px;
}

.menu-icon {
  font-size: 18px;
  color: #666;
  cursor: pointer;
  padding: 5px;
}

.target-icon {
  font-size: 18px;
  color: #666;
  cursor: pointer;
  padding: 5px;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

.loading-text {
  font-size: 16px;
  color: #666;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 错误状态 */
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.error-text {
  font-size: 16px;
  color: #666;
  margin-bottom: 20px;
}

.retry-button {
  background: #007bff;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
}

.retry-button:hover {
  background: #0056b3;
}

/* 指南内容 */
.guide-content {
  padding: 20px;
}

.guide-header {
  background: white;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.guide-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin: 0 0 15px 0;
  line-height: 1.4;
}

.guide-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.guide-date {
  color: #999;
}

.guide-views {
  color: #007bff;
}

.guide-body {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.content-section {
  margin-bottom: 30px;
}

.content-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0 0 15px 0;
  padding-bottom: 8px;
  border-bottom: 2px solid #007bff;
}

.content-text {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  margin: 0;
}

.steps-content {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
}

.steps-content :deep(br) {
  margin-bottom: 8px;
}

.hospital-info {
  font-size: 16px;
  color: #007bff;
  font-weight: 500;
  margin: 0;
}

/* 收藏按钮 */
.collection-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.collection-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #007bff;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: background-color 0.3s ease;
}

.collection-btn:hover {
  background: #0056b3;
}

.collection-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  color: #666;
}

.star-icon {
  font-size: 20px;
  transition: color 0.3s ease;
}

.star-filled {
  color: #ffd700; /* 金色 */
}

.collection-text {
  font-weight: bold;
  transition: color 0.3s ease;
}

.collection-btn:disabled .collection-text {
  color: #999;
}

.loading-dot {
  position: absolute;
  right: 10px;
  width: 8px;
  height: 8px;
  background-color: white;
  border-radius: 50%;
  animation: pulse 1.5s infinite ease-in-out;
}

@keyframes pulse {
  0% {
    transform: scale(0.9);
    opacity: 0.7;
  }
  50% {
    transform: scale(1.1);
    opacity: 1;
  }
  100% {
    transform: scale(0.9);
    opacity: 0.7;
  }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .guide-content {
    padding: 15px;
  }
  
  .guide-header,
  .guide-body {
    padding: 15px;
  }
  
  .guide-title {
    font-size: 18px;
  }
  
  .content-text,
  .steps-content {
    font-size: 15px;
  }
}
</style> 